//
//  CHPluginsController.m
//  DrawIt
//
//  Created by Pieter Omvlee on 1/3/08.
//  Copyright 2008 GetDrawIt. All rights reserved.
//

#import "CHPluginsController.h"

@interface CHPluginsController (Private)
- (void)loadPlugins;
- (NSArray *)pluginPaths;
@end

@implementation CHPluginsController

- (id)init
{
  self = [super init];
  if (self) {
    availablePlugins = [[NSMutableDictionary alloc] init];
    NSString *path;
    NSEnumerator *e = [[self pluginPaths] objectEnumerator];
    while (path = [e nextObject]) {
      NSBundle *bundle = [NSBundle bundleWithPath:path];
      if ([bundle load]) {
        Class class = [bundle principalClass];
        [availablePlugins setValue:path forKey:NSStringFromClass(class)];
      }
    }
  }
  return self;
}

- (NSString *)pluginSubFolder
{
  return @"";
}

- (NSArray *)pluginPaths
{
  NSArray *librarySearchPaths;
  NSEnumerator *searchPathEnum;
  NSString *currPath;
  NSMutableArray *bundleSearchPaths = [NSMutableArray array];
  NSMutableArray *allBundles        = [NSMutableArray array];
  NSString *appName                 = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  NSString *ext                     = @"bundle";
  NSString *appSupportSubpath = [[NSString stringWithFormat:@"Application Support/%@/Plugins",appName] stringByAppendingPathComponent:[self pluginSubFolder]];
  
  librarySearchPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask - NSSystemDomainMask, YES);
  
  searchPathEnum = [librarySearchPaths objectEnumerator];
  while(currPath = [searchPathEnum nextObject]) {
    [bundleSearchPaths addObject:[currPath stringByAppendingPathComponent:appSupportSubpath]];
  }
  [bundleSearchPaths addObject:[[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:[self pluginSubFolder]]];
  
  searchPathEnum = [bundleSearchPaths objectEnumerator];
  while(currPath = [searchPathEnum nextObject]) {
    NSString *currBundlePath;
    NSDirectoryEnumerator *bundleEnum = [[NSFileManager defaultManager] enumeratorAtPath:currPath];
    if (bundleEnum) {
      while (currBundlePath = [bundleEnum nextObject]) {
        if ([[currBundlePath pathExtension] isEqualToString:ext]) {
          [allBundles addObject:[currPath stringByAppendingPathComponent:currBundlePath]];
        }
      }
    }
  }
  
  return allBundles;
}

- (NSArray *)availablePluginNames
{
    return [availablePlugins allKeys];
}

- (id)pluginInstanceWithName:(NSString *)name
{
  NSBundle *bundle = [NSBundle bundleWithPath:[availablePlugins valueForKey:name]];
  if ([bundle load]) {
    Class class = [bundle principalClass];
    return [[[class alloc] init] autorelease];
  }
  return nil;
}

@end
